/*
 * @Author: dadadaXU 1413107032@qq.com
 * @Date: 2025-01-26 22:05:56
 * @LastEditors: dadadaXU 1413107032@qq.com
 * @LastEditTime: 2025-01-26 22:42:09
 * @FilePath: \LeetCode\234.回文链表.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @lc app=leetcode.cn id=234 lang=cpp
 *
 * [234] 回文链表
 *
 * 方法1：快慢指针链表截半 + 前半部分头插法倒置
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
class Solution
{
public:
    bool isPalindrome(ListNode *head)
    {
        ListNode *slow = head;
        ListNode *fast = head->next;
        if (fast == nullptr)
            return true;

        head = nullptr;
        while (true)
        {
            /* 前半部分头插法倒置 */
            ListNode *temp = slow->next;
            slow->next = head;
            head = slow;
            slow = temp;
            /* 快慢指针链表截半 */
            fast = fast->next;
            if (fast != nullptr)
                fast = fast->next;
            else // 偶数个结点
                break;

            if (fast == nullptr) // 奇数个结点
            {
                slow = slow->next;
                break;
            }
        }
        /* 回文判断 */
        fast = head;
        while (fast != nullptr)
        {
            if (fast->val != slow->val)
                return false;

            fast = fast->next;
            slow = slow->next;
        }

        return true;
    }
};
// @lc code=end
